package com.genexususa.eo.google.authorization;

import com.google.api.ads.common.lib.auth.GoogleClientSecretsBuilder;
import com.google.api.ads.common.lib.exception.ValidationException;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.*;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.common.collect.Lists;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class GetRefreshToken {

    private static final String SCOPE = "https://adwords.google.com/api/adwords";

    // This callback URL will allow you to copy the token from the success screen.
    private static final String CALLBACK_URL = "urn:ietf:wg:oauth:2.0:oob";

    private static Credential getOAuth2Credential(GoogleClientSecrets clientSecrets)
            throws Exception {
        GoogleAuthorizationCodeFlow authorizationFlow = new GoogleAuthorizationCodeFlow.Builder(
                new NetHttpTransport(),
                new JacksonFactory(),
                clientSecrets,
                Lists.newArrayList(SCOPE))
                // Set the access type to offline so that the token can be refreshed.
                // By default, the library will automatically refresh tokens when it
                // can, but this can be turned off by setting
                // api.adwords.refreshOAuth2Token=false in your ads.properties file.
                .setAccessType("offline").build();

        String authorizeUrl =
                authorizationFlow.newAuthorizationUrl().setRedirectUri(CALLBACK_URL).build();
        System.out.println("Paste this url in your browser: \n" + authorizeUrl + '\n');

        // Wait for the authorization code.
        System.out.println("Type the code you received here: ");
        String authorizationCode = new BufferedReader(new InputStreamReader(System.in)).readLine();

        // Authorize the OAuth2 token.
        GoogleAuthorizationCodeTokenRequest tokenRequest =
                authorizationFlow.newTokenRequest(authorizationCode);
        tokenRequest.setRedirectUri(CALLBACK_URL);
        GoogleTokenResponse tokenResponse = tokenRequest.execute();

        // Create the OAuth2 credential.
        GoogleCredential credential = new GoogleCredential.Builder()
                .setTransport(new NetHttpTransport())
                .setJsonFactory(new JacksonFactory())
                .setClientSecrets(clientSecrets)
                .build();

        // Set authorized credentials.
        credential.setFromTokenResponse(tokenResponse);

        return credential;
    }

    public static void main(String[] args) throws Exception {
        // Get the client ID and secret from the ads.properties file.
        // If you do not have a client ID or secret, please create one in the
        // API console: https://code.google.com/apis/console#access and set it
        // in the ads.properties file.
        GoogleClientSecrets clientSecrets = null;
        try {
            clientSecrets = new GoogleClientSecretsBuilder()
                    .forApi(GoogleClientSecretsBuilder.Api.ADWORDS)
                    .fromFile()
                    .build();
        } catch (ValidationException e) {
            System.err.println(
                    "Please input your client ID and secret into your ads.properties file, which is either "
                            + "located in your home directory in your src/main/resources directory, or "
                            + "on your classpath. If you do not have a client ID or secret, please create one in "
                            + "the API console: https://code.google.com/apis/console#access");
            System.exit(1);
        }

        // Get the OAuth2 credential.
        Credential credential = getOAuth2Credential(clientSecrets);

        System.out.printf("Your refresh token is: %s\n", credential.getRefreshToken());

        // Enter the refresh token into your ads.properties file.
        System.out.printf("In your ads.properties file, modify:\n\napi.adwords.refreshToken=%s\n",
                credential.getRefreshToken());
    }
}
